<template>
  <q-form ref="form" @submit="onSubmit" class="q-gutter-md q-pb-xl">
    <formInput ref='formInput' :fieldlist="formFields" multipleCol />

    <history v-if="mode === 'edit'" class="q-mb-xl" :data="historyData" :escape="historyEscape" :tableFields="tableFields" />

    <q-page-sticky position="bottom" :offset="[0, 28]">
      <q-btn label="保存" type="submit" color="primary" class="btn-fixed-width" icon="save" :loading="saving" v-if="canSave" />
      <q-btn label="返回" @click="onReset" color="primary" outline class="q-ml-md bg-white" />
    </q-page-sticky>
  </q-form>
</template>

<script>
import { defineComponent } from 'vue';
import formInput from 'src/components/FormInput.vue';
import { detailPageMix } from 'src/lib/mixin.js';
import history from 'src/components/history.vue'
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';
import { encrypt, decrypt } from 'app/src-ssr/util/crypto.js';
import { isNumber } from 'src/lib/utils.js';

export default defineComponent({
  name: 'materialDetail',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '货物档案';
    const moduleName = 'material';
    const detailApi = `/c2/tenant/${moduleName}/detail`; // 明细数据接口
    const createApi = `/c2/tenant/${moduleName}/create`; // 新建数据接口
    const updateApi = `/c2/tenant/${moduleName}/update`; // 更新数据接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}详情 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      detailApi,
      createApi,
      updateApi
    }
  },
  components: {
    formInput,
    history
  },
  inject: ['reload'], // 引用
  mixins: [detailPageMix],
  data () {
    return {
      formFields: {
        images: { type: 'image', label: '货物图片', value: [], fullwidth: true, readonly: false },
        sep1: { type: 'separator', label: '货物分类' },
        catalog_id1: { type: 'select', label: '一级分类', value: '', options: [], selected: [], readonly: false },
        catalog_id2: { type: 'select', label: '二级分类', value: '', options: [], selected: [], readonly: false },
        catalog_id3: { type: 'select', label: '三级分类', value: '', options: [], selected: [], readonly: false },
        catalog_id4: { type: 'select', label: '四级分类', value: '', options: [], selected: [], readonly: false },
        sep2: { type: 'separator', label: '货物信息' },
        material_no: { type: 'input', label: '货物编码', value: '', rules: [this.checkMaterialNo], hint: '留空，系统自动生成', readonly: false },
        material_name: { type: 'autocomplete', label: '货物名称 *', value: '', rules: [this.checkMaterialName], options: [], readonly: false },
        material_model: { type: 'autocomplete', label: '货物规格', value: '', rules: [this.checkMaterialName], options: [], readonly: false },
        material_unit: { type: 'input', label: '计量单位 *', value: '', rules: [val => !!val || '请输入计量单位'], readonly: false },
        material: { type: 'input', label: '材质或色号', value: '', autogrow: true, readonly: false },
        brand: { type: 'input', label: '品牌', value: '', readonly: false },
        origin: { type: 'input', label: '产地', value: '', readonly: false },
        barcode: { type: 'input', label: '条码编号', value: '', readonly: false },
        remark: { type: 'input', label: '备注', value: '', autogrow: true, readonly: false },
        sep3: { type: 'separator', label: '销售设置' },
        sale_price: { type: 'input', label: '销售单价', value: '', suffix: '元', hint: '若要上架销售，需要输入销售单价', rules: [val => (val === '' || isNumber(val)) || '请输入数值型数据'], readonly: false },
        describe: { type: 'richedit', label: '货物详情', value: '', fullwidth: true, readonly: false },
        sell: { type: 'toggle', label: '是否上架', value: 1, trueValue: 1, trueLabel: '是', falseValue: 0, falseLabel: '否', readonly: false },
        recommend: { type: 'toggle', label: '是否推荐', value: 1, trueValue: 1, trueLabel: '是', falseValue: 0, falseLabel: '否', readonly: false }
      },
      tree: [],
      init: true
    };
  },
  async mounted () {
    await this.refreshCatalog();

    if (this.mode === 'add') {
      // 克隆
      if (this.idEx.length > 0) {
        this.$axios.post(this.detailApi, { id: this.idEx[0] }).then(({ data }) => {
          for (const key in data) {
            if (this.formFields[key] && ['id', 'material_no'].indexOf(key) < 0) {
              this.formFields[key].value = data[key];
            }
          }

          // 给分类1赋值
          this.initCatalog(data.catalog_id1);
        });
      } else { // 新增空白
        if (this.$route.query.c1) {
          // 给分类1赋值
          this.initCatalog(this.$route.query.c1);
        }
        this.$nextTick(() => {
          this.init = false;
        });
      }
    } else if (this.mode === 'edit') { // 修改
      this.refreshData(() => {
        // 给分类1赋值
        this.initCatalog(this.data.catalog_id1);
      });
    }
  },
  methods: {
    onSubmit () {
      this.$refs.formInput.validateAll();
      this.$nextTick(() => {
        this.$refs.form.validate().then(ot => {
          if (ot) {
            this.saving = true;
            this.$refs.formInput.getFormData().then(data => {
              this.saveData(data, (_err, resData) => {
                if (this.mode === 'add') {
                  this.confirmBox('询问', '继续新增吗？').then(confirm => {
                    if (confirm) {
                      const path = this.$route.path.split('/');
                      path[path.length - 1] = encrypt('-1', this.secretKey);
                      const route = { path: path.join('/') };
                      if (this.$route.query) {
                        route.query = this.$route.query;
                      }
                      this.$router.replace(route);
                      this.reload(); // 重新加载
                    } else {
                      this.onReset();
                    }
                  });
                } else {
                  this.onReset();
                }
              });
            }).catch(e => {
              console.log(e);
              this.saving = false
            });
          }
        });
      });
      // this.saving = true;
      // this.saveData();
    },
    checkMaterialNo (code) {
      return new Promise((resolve, reject) => {
        if (!code) return resolve(null);

        this.$axios.post('/c/system/checkRepeatCode', {
          code: 'MT',
          values: {
            material_no: this.formFields.material_no.value
          },
          exclude: ['id', this.id]
        }).then(({ data }) => {
          resolve(data ? '货物编码重复' : null);
        });
      });
    },
    checkMaterialName (code) {
      return new Promise((resolve, reject) => {
        this.$axios.post('/c/system/checkRepeatCode', {
          code: 'MT',
          values: {
            material_name: this.formFields.material_name.value,
            material_model: this.formFields.material_model.value
          },
          exclude: ['id', this.id]
        }).then(({ data }) => {
          resolve(data ? '货物名称和型号重复' : null);
        });
      });
    },
    async refreshCatalog () {
      const { data } = await this.$axios.post('/c2/tenant/material/catalogList');
      this.tree = data.catalog;
      this.formFields.catalog_id1.options = this.tree[0].children.map(v => {
        return {
          value: v.id,
          label: v.label,
          catalog_code: v.catalog_code,
          catalog_name: v.catalog_name,
          code_rule: v.code_rule,
          children: v.children
        }
      });
    },
    initCatalog (catalog_id) {
      // 给分类1赋值
      const opt = this.formFields.catalog_id1.options.filter(v => v.value == catalog_id);
      if (opt.length > 0) {
        this.formFields.catalog_id1.value = opt[0];
        this.formFields.catalog_id1.selected = opt;
      }

      this.$nextTick(() => {
        this.init = false;
      });
    },
    searchSimilarName (name) {
      const opt = [];
      if (this.dictionary && this.dictionary.material && name) {
        const items = this.dictionary.material.filter(v => v.material_name.replace(/ /g, '').indexOf(name) >= 0);
        opt.push(...new Set(items.map(v => v.material_name)));
      }
      return opt;
    },
    searchSimilarModel (name, model) {
      const opt = [];
      if (this.dictionary && this.dictionary.material && name) {
        let items = this.dictionary.material.filter(v => v.material_name.replace(/ /g, '').indexOf(name) >= 0);
        if (model) {
          items = items.filter(v => String(v.material_model).indexOf(model) >= 0);
        }

        opt.push(...new Set(items.filter(v => v.material_model).map(v => v.material_model)));
      }
      return opt;
    }
  },
  computed: {
  },
  watch: {
    'formFields.catalog_id1.selected' (val) {
      if (val && val[0] && val[0].children && val[0].children.length > 0) {
        this.formFields.catalog_id2.options = val[0].children.map(v => {
          return {
            value: v.id,
            label: v.label,
            catalog_code: v.catalog_code,
            catalog_name: v.catalog_name,
            code_rule: v.code_rule,
            children: v.children
          }
        });

        // 初始化期间
        if (this.init) {
          let opt = [];
          if (this.mode == 'edit') {
            opt = this.formFields.catalog_id2.options.filter(v => v.value == this.data.catalog_id2);
          } else if (this.mode == 'add' && this.$route.query.c2) {
            opt = this.formFields.catalog_id2.options.filter(v => v.value == this.$route.query.c2);
          }

          if (opt.length > 0) {
            this.formFields.catalog_id2.value = opt[0];
            this.formFields.catalog_id2.selected = opt;
          } else {
            this.formFields.catalog_id2.value = '';
            this.formFields.catalog_id2.selected = [];
          }
        }
      } else if (val === null) {
        this.formFields.catalog_id2.options = [];
        this.formFields.catalog_id2.value = '';
        this.formFields.catalog_id2.selected = [];
      } else if (val && val[0] && (!val[0].children || val[0].children.length == 0)) {
        if (this.init && this.mode == 'edit') { // 初始化环境，新增模式

        }
      }
    },
    'formFields.catalog_id2.selected' (val) {
      if (val && val[0] && val[0].children && val[0].children.length > 0) {
        this.formFields.catalog_id3.options = val[0].children.map(v => {
          return {
            value: v.id,
            label: v.label,
            catalog_code: v.catalog_code,
            catalog_name: v.catalog_name,
            code_rule: v.code_rule,
            children: v.children
          }
        });

        // 初始化期间
        if (this.init) {
          let opt = [];
          if (this.mode == 'edit') {
            opt = this.formFields.catalog_id3.options.filter(v => v.value == this.data.catalog_id3);
          } else if (this.mode == 'add' && this.$route.query.c3) {
            opt = this.formFields.catalog_id3.options.filter(v => v.value == this.$route.query.c3);
          }
          if (opt.length > 0) {
            this.formFields.catalog_id3.value = opt[0];
            this.formFields.catalog_id3.selected = opt;
          } else {
            this.formFields.catalog_id3.value = '';
            this.formFields.catalog_id3.selected = [];
          }
        }
      } else if (val === null) {
        this.formFields.catalog_id3.options = [];
        this.formFields.catalog_id3.value = '';
        this.formFields.catalog_id3.selected = [];
      }/*  else if (val && val[0] && (!val[0].children || val[0].children.length == 0)) {
        if (this.init && this.mode == 'edit') { // 初始化环境，新增模式

        }
      } */
    },
    'formFields.catalog_id3.selected' (val) {
      if (val && val[0] && val[0].children && val[0].children.length > 0) {
        this.formFields.catalog_id4.options = val[0].children.map(v => {
          return {
            value: v.id,
            label: v.label,
            catalog_code: v.catalog_code,
            catalog_name: v.catalog_name,
            code_rule: v.code_rule,
            children: v.children
          }
        });
        // 初始化期间
        if (this.init) {
          let opt = [];
          if (this.mode == 'edit') {
            opt = this.formFields.catalog_id4.options.filter(v => v.value == this.data.catalog_id4);
          } else if (this.mode == 'add' && this.$route.query.c4) {
            opt = this.formFields.catalog_id4.options.filter(v => v.value == this.$route.query.c4);
          }
          if (opt.length > 0) {
            this.formFields.catalog_id4.value = opt[0];
            this.formFields.catalog_id4.selected = opt;
          } else {
            this.formFields.catalog_id4.value = '';
            this.formFields.catalog_id4.selected = [];
          }
        }
      } else if (val === null) {
        this.formFields.catalog_id4.options = [];
        this.formFields.catalog_id4.value = '';
        this.formFields.catalog_id4.selected = [];
      }/*  else if (val && val[0] && (!val[0].children || val[0].children.length == 0)) {
        if (this.init && this.mode == 'edit') { // 初始化环境，新增模式
        }
      } */
    },
    'formFields.catalog_id4.selected' (val) {
    },
    'formFields.material_name.value' (val) {
      if (val) {
        this.formFields.material_name.options = this.searchSimilarName(val.trim());
        this.formFields.material_model.options = this.searchSimilarModel(val.trim(), this.formFields.material_model.value.trim());
      } else {
        this.formFields.material_name.options = [];
        this.formFields.material_model.options = [];
      }
    },
    'formFields.material_model.value' (val) {
      if (val) {
        this.formFields.material_model.options = this.searchSimilarModel(this.formFields.material_name.value.trim(), val.trim());
      }
    }
  }
});
</script>
